package com.hkfn.rfb.common.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hkfn.rfb.R;
import com.hkfn.rfb.common.activity.BaseActivity;
import com.hkfn.rfb.common.adapter.BaseRecyclerAdapter;
import com.hkfn.rfb.common.bean.BaseModel;
import com.hkfn.rfb.common.utils.Utils;
import com.hkfn.rfb.common.view.InitView;
import com.hkfn.rfb.common.view.SuperSwipeRefreshLayout;

import java.util.LinkedList;

/**
 * 通用信息流列表
 */
public abstract class InfoListFragment extends BaseFragment implements SuperSwipeRefreshLayout.OnSwipeRefreshListener {

    public BaseActivity activity;
    private Bundle bundle;

    private View itemContentView;

    private SuperSwipeRefreshLayout swipe_container;
    private RecyclerView rlv_info_list;
    private BaseRecyclerAdapter baseRecyclerAdapter;
    private LinearLayoutManager llm_info_list;

    /**
     * 列表底部数据加载状态
     */
    private View footerView;
    private LinearLayout ll_recycler_footer;
    private RelativeLayout rl_no_more_data;

    public View include_no_data;
    public View include_no_net;
    public View include_progress_bar;


    private int total = -1;
    private int currentListSize = 0;
    private int currentPage = 1;
    private boolean isNoMoreData = false;
    private boolean isListLoadOver = true;
    private int lastVisibleItem;

    /**
     * 部分页面onresume会请求数据 防止重复请求 默认oncreate里请求一次
     */
    private boolean needStartLoadData = true;

    public boolean isNoMoreData() {
        return isNoMoreData;
    }

    public void setNoMoreData(boolean noMoreData) {
        isNoMoreData = noMoreData;
    }

    public boolean isNeedStartLoadData() {
        return needStartLoadData;
    }

    public void setNeedStartLoadData(boolean needStartLoadData) {
        this.needStartLoadData = needStartLoadData;
    }

    public BaseRecyclerAdapter getBaseRecyclerAdapter() {
        return baseRecyclerAdapter;
    }

    public void setBaseRecyclerAdapter(BaseRecyclerAdapter baseRecyclerAdapter) {
        this.baseRecyclerAdapter = baseRecyclerAdapter;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            activity = getMyActivity();
            bundle = getArguments();
            getBundleData(bundle);
            itemContentView = inflater.inflate(R.layout.f_common_info_list, container, false);
            initView();
            if (needStartLoadData) {
                loadMoreData(currentPage);
            }
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        swipe_container = itemContentView.findViewById(R.id.swipe_container);
        InitView.instance().initSuperSwipeLayout(swipe_container);
        swipe_container.setOnSwipeRefreshListener(this);
        swipe_container.setHeaderViewBackgroundColor(activity.getResources().getColor(R.color.page_bg_color));

        initListView();

        include_no_data = itemContentView.findViewById(R.id.include_no_data);
        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(activity, include_progress_bar);
        include_no_net = itemContentView.findViewById(R.id.include_no_net);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.hasNetwork(activity)) {
                    include_no_net.setVisibility(View.GONE);
                    updateData();
                }
            }
        });

        initOtherView(itemContentView);
    }

    private void initListView() {
        rlv_info_list = itemContentView.findViewById(R.id.rlv_info_list);

        llm_info_list = initLayoutManager();
        rlv_info_list.setLayoutManager(llm_info_list);

        baseRecyclerAdapter = initListAdapter();
        rlv_info_list.setAdapter(baseRecyclerAdapter);

        initListHeadView(rlv_info_list, baseRecyclerAdapter);

        if (baseRecyclerAdapter.isNeedFooter()) {
            initFooterView();
        }

        baseRecyclerAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<BaseModel>() {
            @Override
            public void onItemClick(View v, int position, BaseModel data) {
                itemClickAction(position, data);
            }
        });

        baseRecyclerAdapter.setOnItemLongClickListener(new BaseRecyclerAdapter.OnItemLongClickListener<BaseModel>() {
            @Override
            public void onItemLongClick(View v, int position, BaseModel data) {
                itemLongClickAction(position, data);
            }
        });

        rlv_info_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == baseRecyclerAdapter.getItemCount()) {
                    bottomLoadMore();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = llm_info_list.findLastVisibleItemPosition();
            }
        });
    }

    public void initListHeadView(RecyclerView recyclerView, BaseRecyclerAdapter baseRecyclerAdapter){}

    private void initFooterView() {
        footerView = LayoutInflater.from(activity).inflate(R.layout.item_common_recyclerview_footer, rlv_info_list, false);
        ll_recycler_footer = footerView.findViewById(R.id.ll_recycler_footer);
        ll_recycler_footer.setVisibility(View.GONE);
        rl_no_more_data = footerView.findViewById(R.id.rl_no_more_data);
        rl_no_more_data.setVisibility(View.GONE);
        baseRecyclerAdapter.setFooterView(footerView);
    }

    @Override
    public void onSwipeRefresh() {
        swipe_container.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipe_container.setRefreshing(false);
                updateData();
            }
        }, 2000);
    }

    @Override
    public void onPushDistanceMoreAction(int distance) {

    }

    @Override
    public void onPullEnableMoreAction(boolean enable) {

    }

    @Override
    public void updateData() {
        super.updateData();
        isNoMoreData = false;
        total = -1;
        currentListSize = 0;
        currentPage = 1;
        loadMoreData(currentPage);
    }

    private void bottomLoadMore(){
        if (include_no_net.isShown() || include_no_data.isShown()
                || isNoMoreData || !isListLoadOver){
            return;
        }
        currentPage++;
        setFooterStyle(1);
        loadMoreData(currentPage);
    }

    /**
     * 0不显示 1正在加载中 2无更多数据
     * @param style
     */
    private void setFooterStyle(int style){
        if (baseRecyclerAdapter.isNeedFooter()) {
            switch (style) {
                case 1:
                    footerView.setVisibility(View.VISIBLE);
                    ll_recycler_footer.setVisibility(View.VISIBLE);
                    rl_no_more_data.setVisibility(View.GONE);
                    break;
                case 2:
                    footerView.setVisibility(View.VISIBLE);
                    ll_recycler_footer.setVisibility(View.GONE);
                    rl_no_more_data.setVisibility(View.VISIBLE);
                    isNoMoreData = true;
                    break;
                default:
                    footerView.setVisibility(View.GONE);
                    break;
            }
        }
    }

    /**
     * 加载更多
     */
    public void loadMoreData(int currentPage){
//        if (Utils.hasNetwork(activity)){
//            include_no_net.setVisibility(View.GONE);
//        }else {
//            include_no_net.setVisibility(View.VISIBLE);
//            return;
//        }
        isListLoadOver = false;
        include_progress_bar.setVisibility(View.VISIBLE);
    }

    /**
     * 数据加载错误
     */
    public void loadErrorAction(){
        include_progress_bar.setVisibility(View.GONE);
        setFooterStyle(0);
        currentPage--;
        isListLoadOver = true;
    }

    /**
     * 设置列表数据
     * @param list
     */
    public void setListData(LinkedList<BaseModel> list, int total) {
        this.total = total;
        setListData(list);
    }

    /**
     * 设置列表数据
     * @param list
     */
    public void setListData(LinkedList<BaseModel> list) {
        isListLoadOver = true;
        include_progress_bar.setVisibility(View.GONE);

        if (null == list || list.size() == 0){
            if (currentPage == 1){
                baseRecyclerAdapter.clear();
                include_no_data.setVisibility(View.VISIBLE);
            }else {
                setFooterStyle(2);
            }
            return;
        }
        include_no_data.setVisibility(View.GONE);
        setFooterStyle(0);
        if (currentPage == 1){
            baseRecyclerAdapter.clear();
        }
        baseRecyclerAdapter.addDatas(list);

        currentListSize += list.size();
        if (total > -1 && currentListSize == total){
            setNoMoreData(true);
        }
    }

    /**
     * 初始化其他控件
     * @param itemContentView
     */
    public void initOtherView(View itemContentView) {
    }

    /**
     * 获取bundle数据
     * @param bundle
     */
    public abstract void getBundleData(Bundle bundle);

    /**
     * 初始化LayoutManager
     * @return
     */
    public abstract LinearLayoutManager initLayoutManager();

    /**
     * 初始化列表适配器
     * @return
     */
    public abstract BaseRecyclerAdapter initListAdapter();

    /**
     * 列表点击动作
     * @param position
     * @param data
     */
    public abstract void itemClickAction(int position, BaseModel data);

    /**
     * 列表长按动作
     * @param position
     * @param data
     */
    public void itemLongClickAction(int position, BaseModel data){}

    /**
     * 取消下拉刷新
     */
    public void setNoRefresh(){
        if (null != swipe_container){
            swipe_container.setEnabled(false);
        }
    }

    public void notifyAdapter(){
        if (null != baseRecyclerAdapter){
            baseRecyclerAdapter.notifyDataSetChanged();
        }
    }
}
